<template>
    <div class="search-to">
        <div class="search-top">
            <div class="search-box">
                <div class="search-input">
                    <input class="input" :placeholder="holderText" v-model="searchName"/>
                </div>
                <svg class="icon-qk" aria-hidden="true" v-if="hasContent" @click="clear">
                    <use xlink:href="#icon-photo-close"></use>
                </svg>
            </div>
            <div class="search-confirm" @click="confirm">搜索</div>
        </div>
        <div class="search-result">
            <scroll class="result-content" :data="searchList" :probeType="2" :preventDefault="true" @pullingUp="onPullingUp" :pullUpLoad="true">
                <div v-if="searchList.length > 0">
                    <list-goods :goods-list="searchList" @toDetail="toDetail" @add="toAddCart"/>
                </div>
                <div  class="no-result" v-else>
                    <p>暂时没有找到相关信息</p>
                </div>
            </scroll>
        </div>
        <product-spec :pro-content="specGood"
                      operation="add"
                      ref="fspec"
                      @chooseDone="specChooseOk"
                      v-if="specGood.key"
        />
    </div>
</template>

<script>
    import API from '../../request/api'
    import Scroll from '@/components/common/scroll';
    import ListGoods from "../../components/Online/list-goods";
    import Problem from "../User/problem";
    import ProductSpec from "../../components/Online/product-spec";
    import {mapActions} from 'vuex';
    export default {
        components: {
            ProductSpec,
            Problem,
            ListGoods,
            Scroll
        },
        name: "search-result",
        data(){
            return{
                holderText:'请输入商品名称',
                searchName: '',
                searchList: [],
                pageSize: 20,
                pageIndex: 0,
                product:{}, //传入分享的商品信息
                specGood: {}
            }
        },
        props:{},
        computed:{
            hasContent(){
                let show = this.searchName != '' ? true : false;
                return show
            },
            isLogin() {
                let userInfo = this.$store.state.login.userInfo;
                console.log('loginlogin:', JSON.stringify(userInfo), userInfo.role);
                let login = false;
                if(JSON.stringify(userInfo) != '{}'){
                    login = userInfo.role === undefined ? false : true;
                }
                return login;
            }
        },
        created(){
            let data = this.$route.params.searchData;
            let user = this.$store.state.user;
            console.log('searchName-online', data, user);
            if(data) {
                this.searchName = data.goodname;
                this.getSearchContent(this.searchName);
            } else if(user.searchTerm){
                if( user.searchType === 'online'){
                    console.log('searchNameonlineonline', user.searchType);
                    this.searchName = user.searchTerm;
                    this.getSearchContent(this.searchName);
                } else {
                    this.$store.commit('searchName', '')
                }
            }
        },
        methods:{
            ...mapActions(['addToCart']),
            getSearchContent(goodname){
                if(goodname){
                    this.request.get(API.getSearch,{
                        name: goodname,
                        size: this.pageSize,
                        page: this.pageIndex
                    }).then((res) =>{
                        this.$store.commit('searchTerm', this.searchName);
                        this.$store.commit('searchType', 'online');
                        if(res.length  > 0) {
                            this.searchList.push(...res);
                            this.pageIndex++;
                        }
                    })
                }

            },
            confirm(){
                let data = {};
                data.goodname = this.searchName;
                let system = JSON.parse(this.$store.state.login.system);
                system = JSON.stringify(system).substring(0, 1);
                data.system =  system;
                console.log('system', system);
                //将搜索词存入搜索历史缓存
                this.$store.commit('searchHistory', data);
                //将之前的搜索结果清空
                this.searchList = [];
                //将请求页数重新设置为0
                this.pageIndex = 0;
                // 搜索
                this.getSearchContent(this.searchName);
            },
            toDetail(detail) {
                console.log('toDetail', detail);
                this.$router.push({
                    name: 'online-detail',
                    query: {
                        gid: detail.gid,
                    }
                })
            },
            toAddCart(good) {
                let that = this;
                this.specGood = {};
                if (good.status == 3) {
                    this.request.get(API.frontGetMiniGood, {
                        gid: good.gid
                    }).then((res) => {
                        console.log('frontGetMiniGood', res);
                        this.goodId = good.gid;
                        this.specGood = res;
                        this.specGood.pic = good.pic;
                        setTimeout(() => {
                            that.$refs.fspec.show();
                        }, 5);
                    }).catch((err) => {
                        console.error('frontGetMiniGood-err', err);
                    });
                } else {
                    this.$toast('该商品暂不可操作');
                }
            },
            specChooseOk(sku) {
                sku.system = this.$store.state.login.system;
                sku.gid = this.goodId;
                if (sku.buyid) {
                    if (this.isLogin) {
                        // 购物车添加商品（已注册）
                        this.request.post(API.onlineAddCartGoods, {
                            gid: sku.gid,
                            buyid: sku.buyid,
                            num: sku.count,
                        }).then((res) => {
                            console.log('onlineAddCartGoods', res);
                        }).catch((err) => {
                            console.error('onlineAddCartGoods-err', err);
                        });
                    } else {
                        this.addToCart(sku);
                    }
                    this.$toast('加入购物车成功');
                }
            },
            onPullingUp(){
                this.getSearchContent(this.searchName)
            },
            clear(){
                this.searchName = '';
            }
        },
    }
</script>

<style lang='stylus' rel='stylesheet/stylus' scoped>
    @import '~@/assets/main.styl'
    .search-to {
        background-color grayF
        width 100%
        height vw(667)
        /*border 1px solid slateblue*/
    }
    .search-top{
        display flex
        flex-direction row
        padding smallMargin smallMargin 0 smallMargin
    }
    .search-confirm{
        display flex
        justify-content center
        align-items center
        height vw(30)
        word-vw(word14, gray3)
        line-height vw(19)
        margin-left smallMargin
    }
    .search-box {
        height vw(30)
        width vw(307)
        border 1px solid main-color
        border-radius all-radius
        display flex
        align-items center
        & .qb{
            width vw(15)
            height vw(15)
            overflow hidden
            fill main-color
            margin-left middleMargin
        }
        .icon-qk{
            width vw(15)
            height vw(15)
            overflow hidden
            fill gray9
        }
    }
    .search-input{
        /*border salmon 1px solid*/
        word-vw(word12, main-color)
        margin-left middleMargin
        width 75%
        input{
            width 100%
        }
    }
    .search-result{
        // border 1px solid slateblue
        /*margin-top smallMargin*/
        height vw(627)
        word-vw(word12, gray3)
        .history-content{
            display flex
            flex-direction row
            flex-wrap wrap
            .single-history{
                background-color #F2F2F2
                padding vw(5)
                border-radius all-radius
                margin-right middleMargin
                margin-top cellPadding
            }
        }
    }
    .no-result{
        text-align center
        color gray9
        line-height vw(30)
        margin middleMargin
    }
</style>
